package com.zyy.smartcity1129.reservation;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.zyy.smartcity1129.BaseFragment;
import com.zyy.smartcity1129.R;
import com.zyy.smartcity1129.data.CarConsumptionInfo;
import com.zyy.smartcity1129.data.MyCarInfo;
import com.zyy.smartcity1129.data.ReserDBInfo;
import com.zyy.smartcity1129.data.RvReserNowInfo;
import com.zyy.smartcity1129.data.UserInfo;
import com.zyy.smartcity1129.data.city;
import com.zyy.smartcity1129.util.Http;
import com.zyy.smartcity1129.util.PpUtil;
import com.zyy.smartcity1129.util.RvAd;
import com.zyy.smartcity1129.util.XCUtli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ReserMyFragment$
 * @Description: 作用
 * @Author: letquit
 * @CreateDate: 30/11/2021$
 * @Version: 1.0
 */
public class ReserMyFragment extends BaseFragment {
    private RecyclerView rvReserMy;
    private TextView tvReserMyTime;
    private Button btnReserMyTime;
    private TextView ReserMyAdd;
    private Button btnReserMyAdd;
    private Button btnReserMyReser;
    UserInfo.UserBean userBean;
    List<MyCarInfo.RowsBean> myCarList = new ArrayList<>();
    List<CarConsumptionInfo.RowsBean> carConList = new ArrayList<>();
    List<RvReserNowInfo> reserNowInfoList = new ArrayList<>();
    RvAd<RvReserNowInfo> rvAd;
    private int id;
    private String date = "";
    List<city.DataBean> citys;
    //    spinner list
    List<String> sProvince, sCity, sDistrict;
    private FrameLayout framePCity1;
    private Spinner spinnerPProvince;
    private Spinner spinnerPCity;
    private Spinner spinnerPDistrict;
    private EditText editPAdd;
    private Button btnPAdd;
    private FrameLayout framePCity2;
    String province, city, district;
    int provinceId;
    String mAddress = "";

    @Override
    protected int layId() {
        return R.layout.f_reser_my;
    }

    @Override
    protected String title() {
        return null;
    }

    @Override
    protected boolean back() {
        return false;
    }

    @Override
    protected Boolean bottom() {
        return null;
    }

    @Override
    protected void init(View iv) {
        ReservationFragment.mutableLiveData.postValue("立即预约");
        initView(iv);
        XCUtli xcUtli = new XCUtli(3);
        xcUtli.then(() -> {
            myCarList = Http.getInstance().get("/prod-api/api/park/car/my", null, MyCarInfo.class, 1).getRows();
            xcUtli.addint();
        });
        xcUtli.then(() -> {
            userBean = Http.getInstance().get("/prod-api/api/common/user/getInfo", null, UserInfo.class, 1).getUser();
            xcUtli.addint();
        });
        xcUtli.then(() -> {
            carConList = Http.getInstance().get("/prod-api/api/park/car/consumption", null, CarConsumptionInfo.class, 1).getRows();
            xcUtli.addint();
        });
        xcUtli.XCliveData.observe(getViewLifecycleOwner(), atomicInteger -> {
            if (atomicInteger.get() == 3) {
                initDataList();
                initAdapter(reserNowInfoList);
                rvReserMy.setLayoutManager(new LinearLayoutManager(getContext()));
                rvReserMy.setAdapter(rvAd);
            }
        });
        btnReserMyAdd.setOnClickListener(view -> {
            initAddData();
        });
        btnReserMyTime.setOnClickListener(view -> {
            new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//                    Toast.makeText(getContext(), year + "-" + (month + 1) + "-" + dayOfMonth + "预约成功", Toast.LENGTH_SHORT).show();
                    date += year + "-" + (month + 1) + "-" + dayOfMonth + " ";
                    new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int hour, int minute) {
                            if (minute < 10) {
                                date += hour + ":" + "0" + minute;
                            } else {
                                date += hour + ":" + minute;
                            }
                            tvReserMyTime.setText(date);
                        }
                    }, 0, 0, true).show();
                }
            }, 2021, 11, 1).show();
        });
        btnReserMyReser.setOnClickListener(view -> {
            Map<String, Boolean> checkStatus = getCheck();
            for (Map.Entry<String, Boolean> entry : checkStatus.entrySet()) {
                Log.i("TAG", entry.getKey() + " " + entry.getValue());
                if (entry.getValue()) {
                    String address = ReserMyAdd.getText().toString().trim();
                    String time = tvReserMyTime.getText().toString().trim();
                    String plateNo = entry.getKey();
                    if (!address.equals("") && !time.equals("") && !plateNo.equals("")) {
                        Log.i("TAG", "车牌号" + plateNo + " 地址" + address + " 时间" + time);
                        long result = new ReserDataAdapter().insert(getContext(), new ReserDBInfo(
                                plateNo, address, time
                        ));
                        Log.i("TAG", String.valueOf(result));
                        if (id != 0) {
                            Toast.makeText(getContext(), "预约成功", Toast.LENGTH_SHORT).show();
                            ReservationFragment.bottomReser.setSelectedItemId(R.id.itemCar);
                        } else {
                            Toast.makeText(getContext(), "预约失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

        });
    }

    private void initAddData() {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(getActivity().getAssets().open("省市区三级联动.txt"));
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String m;
            StringBuilder stringBuilder = new StringBuilder();
            while ((m = bufferedReader.readLine()) != null) {
                stringBuilder.append(m);
            }
            citys = new Gson().fromJson(stringBuilder.toString(), city.class).getData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        sProvince = new ArrayList<>();
        sCity = new ArrayList<>();
        sDistrict = new ArrayList<>();
        for (city.DataBean c : citys) {
            sProvince.add(c.getProvinceName());
        }
        ArrayAdapter<String> ads1 = new ArrayAdapter(getContext(), R.layout.sp_item, sProvince);
        ArrayAdapter<String> ads2 = new ArrayAdapter(getContext(), R.layout.sp_item, sCity);
        ArrayAdapter<String> ads3 = new ArrayAdapter(getContext(), R.layout.sp_item, sDistrict);
        PpUtil ppUtil = new PpUtil();
        View view = ppUtil.getP(requireContext(), R.layout.p_city);
        framePCity1 = (FrameLayout) view.findViewById(R.id.framePCity1);
        spinnerPProvince = (Spinner) view.findViewById(R.id.spinnerPProvince);
        spinnerPCity = (Spinner) view.findViewById(R.id.spinnerPCity);
        spinnerPDistrict = (Spinner) view.findViewById(R.id.spinnerPDistrict);
        editPAdd = (EditText) view.findViewById(R.id.editPAdd);
        btnPAdd = (Button) view.findViewById(R.id.btnPAdd);
        framePCity2 = (FrameLayout) view.findViewById(R.id.framePCity2);
        spinnerPProvince.setAdapter(ads1);
        spinnerPCity.setAdapter(ads2);
        spinnerPDistrict.setAdapter(ads3);
        spinnerPProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = (String) parent.getItemAtPosition(position);
                sCity.clear();
                province = sProvince.get(position);
                provinceId = position;
                for (city.DataBean.MallCityListBean mBean : citys.get(position).getMallCityList()) {
                    sCity.add(mBean.getCityName());
                }
                ads2.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinnerPCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = (String) parent.getItemAtPosition(position);
                Log.i("TAG", str);
                sDistrict.clear();
                city = sCity.get(position);
                for (city.DataBean.MallCityListBean.MallAreaListBean mBean : citys.get(provinceId).getMallCityList().get(position).getMallAreaList()) {
                    sDistrict.add(mBean.getAreaName());
                }
                ads3.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinnerPDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = (String) parent.getItemAtPosition(position);
                Log.i("TAG", str);
                district = sDistrict.get(position);
                mAddress = province + city + district;
                Toast.makeText(getContext(), "当前：" + mAddress, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        btnPAdd.setOnClickListener(view1 -> {
            String moreAddress = editPAdd.getText().toString();
            if (!moreAddress.equals("")) {
                if (!mAddress.equals("")) {
                    String address = mAddress + moreAddress;
                    ReserMyAdd.setText(address);
                    ppUtil.closeP();
                } else {
                    Toast.makeText(getContext(), "请选择地址", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "请输入完整地址", Toast.LENGTH_SHORT).show();
            }
        });
        framePCity1.setOnClickListener(view1 -> {
            ppUtil.closeP();
        });
        framePCity2.setOnClickListener(view1 -> {
            ppUtil.closeP();
        });
    }

    //    记录所选CheckBox
    private Map<String, Boolean> checkStatus = new HashMap<>();
    private Map<Integer, Boolean> map = new HashMap<>();

    //    获取所选CheckBox状态
    public Map<String, Boolean> getCheck() {
        return checkStatus;
    }

    //    将CheckBox状态插入Map
    public void setCheck(String position, boolean isChecked) {
        checkStatus.put(position, isChecked);
        ;
    }

    private void initAdapter(List<RvReserNowInfo> reserNowInfoList) {
        rvAd = new RvAd<RvReserNowInfo>(reserNowInfoList, R.layout.r_reser_now) {
            private void initView(View vi) {
                tvRvPlateNo = (TextView) vi.findViewById(R.id.tvRvPlateNo);
                tvRvType = (TextView) vi.findViewById(R.id.tvRvType);
                tvRvTravelDistance = (TextView) vi.findViewById(R.id.tvRvTravelDistance);
                tvRvPhonenumber = (TextView) vi.findViewById(R.id.tvRvPhonenumber);
                imgRvReserNowDel = (ImageView) vi.findViewById(R.id.imgRvReserNowDel);
                checkRvReserNow = (CheckBox) vi.findViewById(R.id.checkRvReserNow);
            }


            private TextView tvRvPhonenumber;
            private TextView tvRvTravelDistance;
            private TextView tvRvType;
            private TextView tvRvPlateNo;
            private ImageView imgRvReserNowDel;
            private CheckBox checkRvReserNow;

            @Override
            protected void initR(View vi, RvReserNowInfo rvReserNowInfo, int p) {
                initView(vi);
                imgRvReserNowDel.setVisibility(View.GONE);
                checkRvReserNow.setVisibility(View.VISIBLE);
                tvRvPlateNo.setText("车牌号：" + rvReserNowInfo.getPlateNo());
                tvRvType.setText("车辆类型：" + rvReserNowInfo.getType());
                tvRvTravelDistance.setText("公里数：" + rvReserNowInfo.getTravelDistance());
                tvRvPhonenumber.setText("手机号：" + rvReserNowInfo.getPhonenumber());
                id = rvReserNowInfo.getId();
                //        监听CheckBox状态
                checkRvReserNow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        setCheck(rvReserNowInfo.getPlateNo(), checkRvReserNow.isChecked());
                        if (b) {
                            map.put(p, true);
                            checkStatus.put(rvReserNowInfo.getPlateNo(), b);
                        } else {
                            map.remove(p);
                        }
                    }
                });
            }
        };
    }

    private void initDataList() {
        for (int i = 0; i < myCarList.size(); i++) {
            String travelDistance = "暂无里程数";
            for (int y = 0; y < carConList.size(); y++) {
                if (myCarList.get(i).getPlateNo().equals(carConList.get(y).getPlateNo())) {
                    travelDistance = String.valueOf(carConList.get(y).getTravelDistance());
                }
            }
            reserNowInfoList.add(new RvReserNowInfo(myCarList.get(i).getId(), myCarList.get(i).getPlateNo(), myCarList.get(i).getType(), travelDistance, userBean.getPhonenumber()));
        }
    }

    private void initView(View iv) {
        rvReserMy = (RecyclerView) iv.findViewById(R.id.rvReserMy);
        tvReserMyTime = (TextView) iv.findViewById(R.id.tvReserMyTime);
        btnReserMyTime = (Button) iv.findViewById(R.id.btnReserMyTime);
        ReserMyAdd = (TextView) iv.findViewById(R.id.ReserMyAdd);
        btnReserMyAdd = (Button) iv.findViewById(R.id.btnReserMyAdd);
        btnReserMyReser = (Button) iv.findViewById(R.id.btnReserMyReser);
    }
}
